package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.RightsMapper;
import com.jt.pojo.Rights;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RightsServiceImpl implements RightsService {
    @Autowired
    private RightsMapper rightsMapper;

    /**
     * 查询一级/二级菜单
     * 查询条件：一级菜单——pid = 0
     *         二级菜单——pid = 一级id
     * @return
     */
    @Override
    public List<Rights> findRightsList() {
        //1.查询一级菜单
        QueryWrapper<Rights> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0);
        List<Rights> oneList = rightsMapper.selectList(queryWrapper);
        //2.查询二级菜单  父子关系封装（重要）
        for (Rights rights : oneList) {
            //获取一级菜单id
            //清空之前的条件
            queryWrapper.clear();
            queryWrapper.eq("parent_id", rights.getId());
            //作为where条件查询
            List<Rights> twoList = rightsMapper.selectList(queryWrapper);
            //将查询出的二级菜单放入一级的Children
            rights.setChildren(twoList);
        }
        //完毕后，onList就包含了一级菜单以及二级菜单的所有数据
        return oneList;
    }

    @Override
    public List<Rights> findRightsListXML() {
        //获取一二级菜单
        List<Rights> rightsList = rightsMapper.findRightsXML();
        //一级菜单List
        List<Rights> parentList = new ArrayList<>();
        //二级菜单List
        List<Rights> childrenList = new ArrayList<>();
        //临时存放二级菜单的List
        List<Rights> child = new ArrayList<>();
        //获取一级、二级菜单List
        for (Rights rights : rightsList) {
            if (rights.getParentId() == 0){
                parentList.add(rights);
            }else if (rights.getLevel() == 2){
                childrenList.add(rights);
            }
        }
        //判断一级菜单ID == 二级菜单父ID
        for (Rights parent : parentList) {
            for (Rights children : childrenList) {
                if (parent.getId() == children.getParentId()){
                    //说明是这个一级菜单的子级
                    child.add(children);
                }
            }
            //如果直接传入child的话就不能用clear，因为set进去的也是child，引用的是同一个地址
            parent.setChildren(new ArrayList<>(child));
            child.clear();
        }

//        for (Rights parent : parentList) {
//            System.out.println(parent);
//        }
        return parentList;
    }
}
